﻿using Serilog;
using Serilog.Events;
using System;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Windows.Forms;
using WatchDog.ConfigManages;

namespace WatchDog.WinForm
{
    public partial class Form1 : Form
    {
        string serviceFilePath = Path.Combine(Application.StartupPath, "WatchDog.WinService.exe");
        string serviceName = "ZWatchDog";

        private ConfigManage _configManage = new ConfigManage();
        private System.Timers.Timer _timer;


        public Form1()
        {
            InitializeComponent();


            this.comboBox1.Items.AddRange(new object[] {
            "生产模式",
            "调试模式"});
            this.comboBox1.SelectedItem = "调试模式";
            this.comboBox1.SelectedValueChanged += (s, e) =>
            {
                if (this.comboBox1.SelectedItem.ToString() == "调试模式")
                {
                    Serilog.loggingLevelSwitch.MinimumLevel = LogEventLevel.Debug;
                    WindowsServiceManage.ExecuteCommand(serviceName, WindowsServiceCustomCommands.ServiceLogLevelDebug);
                }
                else
                {
                    Serilog.loggingLevelSwitch.MinimumLevel = LogEventLevel.Warning;
                    WindowsServiceManage.ExecuteCommand(serviceName, WindowsServiceCustomCommands.ServiceLogLevelWarning);
                }
            };

            using (var client = new SqliteDbContext())
            {
                client.Database.EnsureCreated();
            }
            _configManage = new ConfigManage();
            _configManage.DataChanged += (s, e) =>
            {
                WindowsServiceManage.ExecuteCommand(serviceName, WindowsServiceCustomCommands.WatchItemChanged);
            };

            dataGridView1.ReadOnly = true;
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.AllowUserToAddRows = false;
            //dataGridView1.Enabled = false;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
            //dataGridView1.RowHeadersVisible = true;

            //设置cell背景透明
            //dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Transparent;
            //dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            //dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //加上这句前面的才起作用
            //dataGridView1.EnableHeadersVisualStyles = false;

            dataGridView1.Columns.Add(new DataGridViewColumn()
            {
                Name = "序号",
                HeaderText = "序号",
                CellTemplate = new DataGridViewTextBoxCell(),
                AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells,
                MinimumWidth = 40
            });
            foreach (var item in new string[] { "ID", "名称", "状态", "运行时长(分)", "自动启动", "文件目录" })
            {
                var col = new DataGridViewColumn
                {
                    Name = item,
                    HeaderText = item,
                    CellTemplate = new DataGridViewTextBoxCell(),
                    AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
                };
                if (item == "ID")
                    col.Visible = false;
                if (item == "文件目录")
                {
                    col.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }
                dataGridView1.Columns.Add(col);
            }



            var data = _configManage.GetFileInfo();
            var dtRows = new DataGridViewRow[data.Count];
            for (int i = 0; i < data.Count; i++)
            {
                dtRows[i] = new DataGridViewRow();
                dtRows[i].CreateCells(dataGridView1);
                //dtRows[i].HeaderCell = new DataGridViewRowHeaderCell();
                //dtRows[i].HeaderCell.Value = (i + 1).ToString();
                //dtRows[i].HeaderCell.Style
                dtRows[i].Cells[1].Value = data[i].Id;
                dtRows[i].Cells[2].Value = data[i].FileName;
                dtRows[i].Cells[3].Value = ProcessHelper.IsStarting(data[i].FilePath) ? "运行中" : "未运行";
                dtRows[i].Cells[4].Value = ProcessHelper.GetStatus(data[i].FilePath).ToString("F2");
                dtRows[i].Cells[5].Value = data[i].AutoStart == true ? "是" : "否";
                dtRows[i].Cells[6].Value = data[i].FilePath;
            }
            dataGridView1.Rows.AddRange(dtRows);


            dataGridView1.RowPostPaint += (s, e) =>
            {
                ////获取行对象
                //var row = dataGridView1.Rows[e.RowIndex];
                ////对行的第一列value赋值
                //row.Cells[0].Value = row.Index + 1;

                var grid = s as DataGridView;
                var rowidx = (e.RowIndex + 1).ToString();
                var centerFormat = new StringFormat()
                {
                    Alignment = StringAlignment.Center,
                    LineAlignment = StringAlignment.Center
                };
                var headerBuunds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
                e.Graphics.DrawString(rowidx, new Font("宋体", 11), SystemBrushes.ControlText, headerBuunds, centerFormat);
            };

            this.progressBar1.Maximum = 100;

            _timer = new System.Timers.Timer(1000) { AutoReset = true };
            _timer.Elapsed += (sender, eventArgs) =>
            {
                UpdateDataGridView();

                UpdateServiceStatus();
            };

            this.VisibleChanged += (s, e) =>
            {
                if (this.Visible)
                    _timer.Start();
                else _timer.Stop();
            };
        }

        public void UpdateServiceStatus()
        {
            this.Invoke(new Action(() =>
            {
                var progress = this.progressBar1.Value + 1;
                if (progress > 100)
                {
                    this.progressBar1.Value = 0;
                }
                else
                {
                    this.progressBar1.Value = progress;
                }


                if (WindowsServiceManage.IsServiceExisted(serviceName))
                {
                    var status = WindowsServiceManage.GetServiceStatus(serviceName);
                    if (status == ServiceControllerStatus.Running)
                    {
                        this.label1.ForeColor = Color.Green;
                        this.label1.Text = "运行中";
                    }
                    else if (status == ServiceControllerStatus.Stopped)
                    {
                        this.label1.ForeColor = Color.Blue;
                        this.label1.Text = "停止";
                    }
                    else
                    {
                        this.label1.ForeColor = Color.Yellow;
                        this.label1.Text = status.ToString();
                    }
                }
                else
                {
                    this.label1.ForeColor = Color.Red;
                    this.label1.Text = "服务未安装";
                }
            }));
        }

        private void UpdateDataGridView()
        {
            try
            {
                this.Invoke(new Action(() =>
                {
                    var index = 0;
                    if (dataGridView1.SelectedRows.Count > 0)
                        index = dataGridView1.SelectedRows[0].Index;//.DataBoundItem as FileView;

                    var data = _configManage.GetFileInfo();


                    DataGridViewRow[] dtRows = new DataGridViewRow[data.Count];
                    for (int i = 0; i < data.Count; i++)
                    {
                        dtRows[i] = new DataGridViewRow();
                        dtRows[i].CreateCells(dataGridView1);
                        //dtRows[i].HeaderCell.Value = (i + 1).ToString();
                        dtRows[i].Cells[1].Value = data[i].Id;
                        dtRows[i].Cells[2].Value = data[i].FileName;
                        dtRows[i].Cells[3].Value = ProcessHelper.IsStarting(data[i].FilePath) ? "运行中" : "未运行";
                        dtRows[i].Cells[4].Value = ProcessHelper.GetStatus(data[i].FilePath).ToString("F2");
                        dtRows[i].Cells[5].Value = data[i].AutoStart == true ? "是" : "否";
                        dtRows[i].Cells[6].Value = data[i].FilePath;
                    }
                    dataGridView1.Rows.Clear();
                    dataGridView1.Rows.AddRange(dtRows);
                    //dataGridView1.Refresh();
                    //dataGridView1.Update();

                    if (index > 0 && index < data.Count)
                        dataGridView1.Rows[index].Selected = true;
                    else if (dataGridView1.Rows.Count > 0)
                        dataGridView1.Rows[0].Selected = true;

                    //foreach (var item in data.Item2)
                    //{
                    //    list.Add(new FileView
                    //    {
                    //        Id = item.Id,
                    //        位置 = item.FilePath,
                    //        名称 = item.FileName,
                    //        状态 = ProcessHelper.IsStarting(item.FilePath) ? "运行中" : "未运行",
                    //        运行时长_分 = ProcessHelper.GetStatus(item.FilePath).ToString("F2"),
                    //        自动启动 = item.AutoStart == true ? "是" : "否"
                    //    });
                    //}
                    //dataGridView1.DataSource = list;

                    //if (index > 0)
                    //    dataGridView1.Rows[index].Selected = true;

                    //dataGridView1.AutoResizeColumn(0, DataGridViewAutoSizeColumnMode.DisplayedCells);
                    //dataGridView1.AutoResizeColumn(1, DataGridViewAutoSizeColumnMode.DisplayedCells);
                    //dataGridView1.AutoResizeColumn(2, DataGridViewAutoSizeColumnMode.DisplayedCells);
                    //dataGridView1.AutoResizeColumn(3, DataGridViewAutoSizeColumnMode.DisplayedCells);
                    //dataGridView1.AutoResizeColumn(4, DataGridViewAutoSizeColumnMode.DisplayedCells);
                }));
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex, "");
            }
        }



        private void add_Click(object sender, EventArgs e)
        {
            var s = new SettingForm(_configManage);
            var xx = s.ShowDialog();
        }
        private void btnEdit_Click(object sender, EventArgs e)
        {
            var fileInfo = GetDataGridViewSelectedRow();
            if (fileInfo == null)
            {
                MessageBox.Show("请选择要编辑的数据行");
                return;
            }
            var s = new SettingForm(_configManage, fileInfo);
            var xx = s.ShowDialog();
        }

        private void del_Click(object sender, EventArgs e)
        {
            var fileInfo = GetDataGridViewSelectedRow();
            if (fileInfo == null)
            {
                MessageBox.Show("请选择要删除的数据行");
                return;
            }

            var btn = MessageBoxButtons.YesNoCancel;
            if (MessageBox.Show("确定要删除 " + fileInfo.FileName + " 吗？", "删除数据", btn) == DialogResult.Yes)
            {
                _configManage.Del(fileInfo.Id);
            }
        }
        private WatchItem GetDataGridViewSelectedRow()
        {
            int id = 0;
            if (dataGridView1.SelectedRows.Count > 0)
            {
                int.TryParse(dataGridView1.SelectedRows[0].Cells[1].Value.ToString(), out id);
            }
            if (id == 0)
            {
                return null;
            }
            return _configManage.GetFileInfo().FirstOrDefault(c => c.Id == id);
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            var fileInfo = GetDataGridViewSelectedRow();
            if (fileInfo == null)
            {
                MessageBox.Show("请选择要停止运行的数据行");
                return;
            }

            var btn = MessageBoxButtons.YesNoCancel;
            if (MessageBox.Show("确定要停止 " + fileInfo.FileName + " 吗？", "停止", btn) == DialogResult.Yes)
            {
                _configManage.Update(fileInfo.Id, false);
                ProcessHelper.Stop(fileInfo.FilePath);
            }
        }

        private void buttonAuto_Click(object sender, EventArgs e)
        {
            var fileInfo = GetDataGridViewSelectedRow();
            if (fileInfo == null)
            {
                MessageBox.Show("请选择要切换的数据行");
                return;
            }

            _configManage.Update(fileInfo.Id, !fileInfo.AutoStart);
        }

        //主窗体关闭时不退出应用程序 隐藏即可
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //窗体关闭原因为单击"关闭"按钮或Alt+F4  
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;           //取消关闭操作 表现为不关闭窗体  
                this.Hide();               //隐藏窗体  
            }
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Icon.Dispose();
            this.notifyIcon1.Visible = false;
            this.notifyIcon1.Dispose();
        }

        #region 任务栏
        //任务栏图标上左键双击 —— 显示主界面
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }
        //任务栏图标上右键 —— 显示菜单 
        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示    
                WindowState = FormWindowState.Normal;
                //激活窗体并给予它焦点
                this.Activate();
                ////任务栏区显示图标
                //this.ShowInTaskbar = true;
                ////托盘区图标隐藏
                //notifyIcon1.Visible = false;
            }
        }
        #endregion

        #region 任务栏右键菜单

        private void 显示主程序ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }

        private void 安装服务toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (WindowsServiceManage.IsServiceExisted(serviceName))
            {
                var r = WindowsServiceManage.UninstallService(serviceName);
                if (r != null)
                {
                    MessageBox.Show(r, "卸载原服务时出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            var r2 = WindowsServiceManage.InstallService(serviceFilePath);
            if (r2 != null)
            {
                MessageBox.Show(r2, "安装服务时出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                MessageBox.Show("服务安装成功...");
            }
        }

        private void 启动服务toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (WindowsServiceManage.IsServiceExisted(serviceName))
            {
                var r = WindowsServiceManage.ServiceStart(serviceName);
                if (r != null)
                {
                    MessageBox.Show(r, "启动服务时出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                    MessageBox.Show("启动服务成功...");
            }
        }

        private void 停止服务toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (WindowsServiceManage.IsServiceExisted(serviceName))
            {
                var r = WindowsServiceManage.ServiceStop(serviceName);
                if (r != null)
                {
                    MessageBox.Show(r, "停止服务时出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                    MessageBox.Show("停止服务成功...");
            }
        }

        private void 卸载服务toolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (WindowsServiceManage.IsServiceExisted(serviceName))
            {
                var r = WindowsServiceManage.ServiceStop(serviceName);
                if (r != null)
                {
                    MessageBox.Show(r, "停止服务时出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var r2 = WindowsServiceManage.UninstallService(serviceFilePath);
                if (r2 != null)
                {
                    MessageBox.Show(r2, "卸载服务时出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                    MessageBox.Show("卸载服务成功...");
            }
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var box = MessageBox.Show("确定要退出程序?", "操作确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (box == DialogResult.Yes)
            {
                notifyIcon1.Visible = false;   //设置图标不可见  
                this.Close();                  //关闭窗体  
                this.Dispose();                //释放资源  
                Application.Exit();            //关闭应用程序窗体  
                notifyIcon1.Dispose();
            }
        }

        #endregion

        private void btnRestart_Click(object sender, EventArgs e)
        {
            //在数据变动时/重新启动服务生效
            var r = WindowsServiceManage.ServiceRestart(serviceName);
            if (r != null)
            {
                MessageBox.Show(r, "重启服务时出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            MessageBox.Show("重启服务已完成");
        }


    }



}
